package top.hencter.weibo.fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import top.hencter.weibo.R;
import top.hencter.weibo.bean.LoginResult;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link UserFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class UserFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public UserFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment UserFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static UserFragment newInstance(String param1, String param2) {
        UserFragment fragment = new UserFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        //  实例化 View 组件并且找到 fragment_user 布局文件进行实例化
        View view = inflater.inflate(R.layout.fragment_user, container, false);

        // 实例化账号密码组件
        final EditText account = view.findViewById(R.id.account);
        final EditText password = view.findViewById(R.id.password);

        // 将用户名和密码保存到 SharedPreference 中
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("loginData",
                Context.MODE_PRIVATE);
        String accountStr = sharedPreferences.getString("account", "");
        String passwordStr = sharedPreferences.getString("password", "");
        account.setText(accountStr);
        password.setText(passwordStr);

        final SharedPreferences.Editor editor = sharedPreferences.edit();
        final CheckBox checkBox = view.findViewById(R.id.remember_password);
        Button loginButton = view.findViewById(R.id.login_btn);
        // 登录的点击事件
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 记住密码功能实现，选中则将密码存入
                if (checkBox.isChecked()) {
                    editor.putString("account", account.getText().toString());
                    editor.putString("password", password.getText().toString());
                    editor.commit();
                } else {
                    editor.remove("account");
                    editor.remove("password");
                    editor.commit();
                }
                Login(account.getText().toString(), password.getText().toString());
            }
        });
        return view;
    }

    // 登录方法
    private void Login(String account, String password) {
        Map<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("account", account);
        stringStringHashMap.put("password", password);
        Gson gson = new Gson();
        String json = gson.toJson(stringStringHashMap);
        RequestBody requestBody = RequestBody.create(
                json,
                MediaType.parse("application/json; charset=utf-8"));

        OkHttpClient client;
        client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://129.28.159.96:7001/v1/login")
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e("Failure Info:", e.toString());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                Gson gson = new Gson();
                final LoginResult loginResult = gson.fromJson(
                        response.body().string(),
                        new TypeToken<LoginResult>() {
                        }.getType()
                );
                Log.i("userID [Response Info]:", loginResult.getMsg());

                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        AlertDialog.Builder normalDiaLog = new AlertDialog.Builder(getActivity());
                        normalDiaLog.setTitle("登录提示");
                        normalDiaLog.setMessage(loginResult.getMsg());
                        normalDiaLog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });

                        // 显示对话框
                        normalDiaLog.show();
                    }
                });
            }
        });
    }
}